package com.teame.readbaby;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.teame.readbaby.parser.HomeListParser1;
import com.teame.readbaby.parser.HomeListParser2;
import com.teame.readbaby.util.ConstantValue;
import com.teame.readbaby.util.CopyFileUtils;
import com.teame.readbaby.util.GloableParams;
import com.teame.readbaby.util.Logger;
import com.teame.readbaby.vo.HomeBannerInfo;
import com.teame.readbaby.vo.HomeClassListInfo;

public class HomeActivity extends BaseActivity {
	protected static final String TAG = "HomeActivity";

	ArrayList<HomeBannerInfo> homeBannerList;
	ArrayList<HomeClassListInfo> homeClassrList;

	private EditText editSearchInfo;// 首页搜索框里面的内容：
	private ImageView ok;// 首页搜索按钮：
	private ListView custonInfoListView;// 首页listview列表：
	private Gallery gallery;// 首页大图片：

	private static int MSG_UPDATE = 1;

	private int count_drawble = 0; // 总共的图片大小
	private int cur_index = 0; // 当前图片位置
	private boolean isalive = true;

	// 为Gallery控件设置Adapter
	private HomeBannerListAdapter homeListAdapter;

	@Override
	protected void loadViewLayout() {
		GloableParams.defaultIndex=1;
		setContentView(R.layout.home_activity);
	}

	@Override
	protected void findViewById() {
		editSearchInfo = (EditText) findViewById(R.id.editSearchInfo);
		ok = (ImageView) findViewById(R.id.ok);
		custonInfoListView = (ListView) findViewById(R.id.custonInfoListView);
		gallery = (Gallery) findViewById(R.id.gallery);

	}

	/**
	 * 获取数据，并存入上下两个集合内
	 */
	@Override
	protected void processLogic() {
		
		// 1.请求的url地址：
				String url = ConstantValue.HOST + "/home";
				// // 2.请求的参数，没有为null：
				// Map<String, String> params = new HashMap<String, String>();
				// params.put("keyword","");
				// params.put("page", "");
				// params.put("pageNum", "");
				// params.put("orderby", "");
				// 3.json数据解析器，大家需要按照自己获取的json的结构自己编写，要继承basePaser
				// 4.回调函数：
				getDataFromServer(url, null, new HomeListParser1(),
						new DataCallback<List<HomeBannerInfo>>() {

							@Override
							public void processData(List<HomeBannerInfo> paramObject,
									boolean paramBoolean) {
								
								if (!paramBoolean || paramObject == null) {// 获取失败
									showNoBanner();// 显示没有大图片：
								} else {// 获取成功
									
									homeBannerList = new ArrayList<HomeBannerInfo>();
									
									for (HomeBannerInfo info : paramObject) {
										homeBannerList.add(info);
									}
									
									homeListAdapter = new HomeBannerListAdapter(
											HomeActivity.this);
								}
							}

						});
//				getDataFromServer(url, null, new HomeListParser2(),
//						new DataCallback<List<HomeClassListInfo>>() {
//
//							@Override
//							public void processData(
//									List<HomeClassListInfo> paramObject,
//									boolean paramBoolean) {
//
//
//								if (!paramBoolean || paramObject == null) {// 获取失败
//									showNoBanner();// 显示没有大图片：
//								} else {// 获取成功
//									homeClassrList = new ArrayList<HomeClassListInfo>();
//									for (HomeClassListInfo info : paramObject) {
//										homeClassrList.add(info);
//									}
//									
//									custonInfoListView.setAdapter(new HomeCLassListAdapter(HomeActivity.this));
//								}
//								
//								
//							}
//
//						});

//				homeListAdapter = new HomeBannerListAdapter(
//						this);
				
				// 先放这儿 回头挪到获取成功哪儿去：TODO
				gallery.setAdapter(homeListAdapter);
				//custonInfoListView.setAdapter(new HomeCLassListAdapter(this));
	}

	
	private void showNoBanner() {
		Toast.makeText(this, "获取首页图片失败：请检查网络", 0).show();
	}

	private class HomeBannerListAdapter extends BaseAdapter {
		private ArrayList<Integer> picList = new ArrayList<Integer>();

		private Context context;

		public HomeBannerListAdapter(Context context) {
			this.context = context;

			for (HomeBannerInfo homeBannerInfo : homeBannerList) {
				int resid = 0;

				Log.i(TAG, homeBannerInfo.getPic());// TODO
			}
		}

		@Override
		public int getCount() {
			Log.e(TAG, " " + picList.size());
			return homeBannerList.size();
		}

		@Override
		public Object getItem(int position) {
			return homeBannerList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ImageView img = new ImageView(context);
			
				int imageIcon[] = { R.drawable.a1, R.drawable.a2,
						R.drawable.a3, R.drawable.a4, R.drawable.a5 };

				img.setImageResource(imageIcon[position]);
			return img;
		}
	}

	private class HomeCLassListAdapter extends BaseAdapter {
		private ArrayList<Integer> picList = new ArrayList<Integer>();

		private Context context;

		public HomeCLassListAdapter(Context context) {
			this.context = context;

			for (HomeBannerInfo homeBannerInfo : homeBannerList) {
				int resid = 0;

				Log.i(TAG, homeBannerInfo.getPic());// TODO
			}
		}

		@Override
		public int getCount() {
			Log.e(TAG, " " + picList.size());
			return homeBannerList.size();
		}

		@Override
		public Object getItem(int position) {
			return homeBannerList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {

			}
			Logger.i(TAG, "getview" + position);
			View view = View.inflate(context, R.layout.home_item, null);
			TextView textContent = (TextView) view
					.findViewById(R.id.textContent);
			ImageView imgIcon = (ImageView) view.findViewById(R.id.imgIcon);

			textContent.setText(homeClassrList.get(position).getTitle());

			int imageIcon[] = { R.drawable.home_classify_01,
					R.drawable.home_classify_02, R.drawable.home_classify_03,
					R.drawable.home_classify_04, R.drawable.home_classify_05 };

			imgIcon.setImageResource(imageIcon[position]);

			return view;
		}
	}

	@Override
	protected void setListener() {
		// this.editSearchInfo.setOnClickListener(this);
		// this.ok.setOnClickListener(this);
		custonInfoListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Toast.makeText(getApplicationContext(), "往下走啊走", 1).show();

			}

		});

	}

	@Override
	protected void onClickEvent(View paramView) {
		gallery.setSpacing(0);// 设置图片之间的间隔，如果不加设置 ，图片会叠加。设置为0，表示图片之间无间缝。
		gallery.setOnItemClickListener(new OnItemClickListener() {
			// 设置监听事件 --->当Gallery中的Item处于选中并且被点击触发该事件
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				cur_index = position;
			}
		});
		// 当Gallery中的Item处于选中并且被点击触发该事件 ，在该监听事件中，保证图片播放的同步性
		gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View view,
					int position, long arg3) {
				System.out.println("setOnItemSelectedListener");
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		
		count_drawble = homeListAdapter.getCount();
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (isalive) {
					cur_index = cur_index % count_drawble; // 图片区间[0,count_drawable)
					Log.i(TAG, "cur_index" + cur_index + " count_drawble --"
							+ count_drawble);
					// msg.arg1 = cur_index
					Message msg = mhandler.obtainMessage(MSG_UPDATE, cur_index,
							0);
					mhandler.sendMessage(msg);
					// 更新时间间隔为 2s
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					cur_index++; // 放置在Thread.sleep(2000)
									// ；防止mhandler处理消息的同步性，导致cur_index>=count_drawble
				}
			}
		}).start();

		switch (paramView.getId()) {
		case R.id.ok:
			Intent intent = new Intent(this, SearchActivity.class);
			startActivity(intent);
			break;

		default:
			break;
		}
	}

	
	
	// 通过handler来更新主界面
	// mgallery.setSelection(positon),选中第position的图片，然后调用OnItemSelectedListener监听改变图像
	private Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == MSG_UPDATE) {
				Log.i(TAG, "cur_index" + cur_index);
				gallery.setSelection(msg.arg1);
				// 直接更改图片 ，不触发Gallery.OnItemSelectedListener监听
				// imgSwitcher.setBackgroundResource(imgAdapter.getResId(msg.arg1));
			}
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
	}
	
	
}
